package com.lotterymanage.web.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.lotterymanage.domain.InsideUser;
import com.lotterymanage.service.InsideUserService;
import com.lotterymanage.service.SystemService;

/**
 * 内部用户登录.
 * @author lxz
 * @date Apr 19, 2010
 */
@Controller()
@RequestMapping("/insideUser.do")
public class InsideUserController extends BaseController {

    private static final Logger LOG = Logger.getLogger(InsideUserController.class);
    @Autowired
    private InsideUserService insideUserService;
    @Autowired
    private SystemService systemService;
    /**
     * 登录.
     * @param insideUser InsideUser
     * @param request HttpServletRequest
     * @param model ModelMap
     * @return null
     * @throws Exception Exception
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(params = "method=signIn")
    public String signIn(final InsideUser insideUser, final ModelMap model,
            final HttpServletRequest request) throws Exception {
        //检验验证码是否合法
        String sessionValidateCode = sessionGetAttr(request, "validateing").toString();
        String requestValidateCode = param(request, "validateing");
        if (sessionValidateCode == null || requestValidateCode == null
                || !requestValidateCode.equals(sessionValidateCode)) {
            LOG.error("验证码有误");
            model.put("errorMsg", "验证码有误");
            return "login";
        }
        InsideUser dbInsideUser = this.insideUserService.findInsideUserByAccounts(insideUser.getAccounts());
        //检验用户是否存在
        if (dbInsideUser == null) {
            LOG.error("用户名或密码有误");
            model.put("errorMsg", "用户名或密码有误");
            return "login";
        }
        //判断内部用户的账户是否被冻结
        if (insideUserService.isFreezeUser(dbInsideUser)) {
            LOG.error("该账户已被冻结，请联系系统管理员！");
            model.put("errorMsg", "该账户已被冻结，请联系系统管理员！");
            return "login";
        }
        //验证IP是否有效
        if (!systemService.isValidIp(request.getRemoteAddr())) {
            LOG.error("IP地址有限制");
            model.put("errorMsg", "IP地址有限制");
            return "login";
        }
        //检验用户是否登录成功
        if (!this.insideUserService.isLogin(dbInsideUser, insideUser.getPassWord())) {
            LOG.error("用户名或密码有误");
            model.put("errorMsg", "用户名或密码有误");
            return "login";
        }
        LOG.info("用户登录成功");
        sessionSetAttr(request, "insideUserSession", dbInsideUser);
        return "redirect:index.do";
    }
}
